package com.cloud.base.repository.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.cloud.base.entity.BaseUser;
import com.cloud.base.repository.BaseUserRepCustom;

public class BaseUserRepoImpl implements BaseUserRepCustom {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public List<BaseUser> myQuery() {

		List<BaseUser> datas = stringRedisTemplate.execute(new RedisCallback<List<BaseUser>>() {

			public List<BaseUser> doInRedis(RedisConnection connection) throws DataAccessException {
				List<BaseUser> result = new ArrayList<BaseUser>();
				// key都是以set类型保存的，先查询全部的key
				Set<byte[]> dataKeys = connection.sMembers("BaseUser".getBytes());
				// 根据每个key去查询数据
				for (byte[] dataKey : dataKeys) {
					// 数据是以hash类型保存的，key使用以下格式："BaseUser:UUID"
					String dataKeyStr = "BaseUser:" + new String(dataKey);
					Map<byte[], byte[]> data = connection.hGetAll(dataKeyStr.getBytes());
					// 读取数据，并转换为了BaseUser
					String id = new String(data.get("id".getBytes()));
					String name = new String(data.get("name".getBytes()));
					String password = new String(data.get("password".getBytes()));
					String address = new String(data.get("address".getBytes()));
					BaseUser p = new BaseUser();
					p.setId(Integer.valueOf(id));
					p.setName(name);
					p.setPassword(password);
					p.setAddress(address);
					result.add(p);
				}
				return result;
			}
		});
		return datas;
	}

}
